"""法律思维训练服务"""
from typing import Dict, Any, List, Optional
from datetime import datetime
from app.ai.llm_service import get_llm_service
from app.ai.evaluation_engine import get_evaluation_engine
from app.ai.legalbert_service import get_legalbert_service
from app.services.question_technique_service import question_technique_service
from app.core.database import RedisClient


class LegalThinkingService:
    """法律思维训练服务"""
    
    def __init__(self):
        try:
            self.redis = RedisClient.get_client()
        except Exception as e:
            print(f"警告: Redis连接失败，思维分析记录将不会保存: {e}")
            self.redis = None
        self.llm_service = get_llm_service()
        self.evaluation_engine = get_evaluation_engine()
        self.legalbert = get_legalbert_service()
    
    async def analyze_thinking_process(
        self,
        user_id: str,
        question_id: str,
        user_answer: str,
        user_notes: str,
        correct_answer: str,
        question_content: str,
        question_explanation: str
    ) -> Dict[str, Any]:
        """
        分析用户的法律思维过程
        
        Args:
            user_id: 用户ID
            question_id: 题目ID
            user_answer: 用户答案
            user_notes: 用户的分析笔记
            correct_answer: 正确答案
            question_content: 题目内容
            question_explanation: 题目解析
            
        Returns:
            思维分析结果
        """
        # 构建思维分析提示词
        thinking_prompt = f"""
你是一位资深的法考培训专家，请分析以下学员的法律思维过程，并提供专业的训练建议。

【题目内容】
{question_content}

【学员答案】
{user_answer}

【学员分析过程】
{user_notes if user_notes else "（学员未提供分析过程）"}

【正确答案】
{correct_answer}

【标准解析】
{question_explanation}

请从以下维度分析学员的法律思维：

1. **法律条文理解**：是否准确理解相关法律条文？是否存在理解偏差？
2. **逻辑推理能力**：推理过程是否严谨？是否存在逻辑漏洞？
3. **案例分析能力**：是否能正确识别案例中的关键事实？是否能准确适用法律？
4. **法律思维模式**：思维是否符合法律人的思维方式（三段论、要件分析等）？
5. **知识体系完整性**：是否建立了完整的法律知识体系？

请以JSON格式返回分析结果，包含以下字段：
- thinking_quality_score: 思维质量分数（0-100）
- strengths: 思维优势（数组）
- weaknesses: 思维薄弱点（数组）
- thinking_pattern: 思维模式分析（字符串）
- reasoning_chain: 推理链条分析（字符串）
- improvement_suggestions: 改进建议（数组）
- legal_knowledge_gaps: 法律知识盲点（数组）
"""
        
        try:
            # 使用Legal-BERT提取推理链条（添加错误处理）
            try:
                reasoning_chain = await self.legalbert.extract_legal_reasoning_chain(
                    question_content,
                    user_notes
                )
            except Exception as e:
                print(f"Legal-BERT提取推理链条失败: {e}")
                reasoning_chain = {
                    "major_premise": {"provisions": []},
                    "minor_premise": {"facts": []},
                    "reasoning_completeness": {"level": "未知", "score": 0}
                }
            
            # 使用Legal-BERT提取关键事实和法律实体（添加错误处理）
            try:
                key_facts = await self.legalbert.extract_key_facts(question_content)
            except Exception as e:
                print(f"Legal-BERT提取关键事实失败: {e}")
                key_facts = []
            
            try:
                entities = await self.legalbert.extract_entities(question_content)
            except Exception as e:
                print(f"Legal-BERT提取实体失败: {e}")
                entities = []
            
            # 分析推理链条完整性
            reasoning_completeness = reasoning_chain.get("reasoning_completeness", {})
            
            # 调用LLM进行思维分析（结合Legal-BERT的分析结果）
            enhanced_prompt = f"""
{thinking_prompt}

【Legal-BERT分析结果】
- 推理链条完整性：{reasoning_completeness.get("level", "未知")} ({reasoning_completeness.get("score", 0)}分)
- 大前提（法律条文）：{len(reasoning_chain.get("major_premise", {}).get("provisions", []))} 个
- 小前提（关键事实）：{len(reasoning_chain.get("minor_premise", {}).get("facts", []))} 个
- 提取的法律实体：{len(entities)} 个
"""
            
            try:
                analysis_result = await self.llm_service.analyze_legal_case(enhanced_prompt)
            except Exception as e:
                print(f"LLM分析失败: {e}")
                # 如果LLM调用失败，使用默认分析结果
                analysis_result = {}
            
            # 如果LLM返回的是字符串，尝试解析JSON
            if isinstance(analysis_result, str):
                import json
                try:
                    analysis_result = json.loads(analysis_result)
                except:
                    # 如果解析失败，使用默认结构
                    analysis_result = self._parse_thinking_analysis(analysis_result)
            
            # 确保返回结构完整
            if not isinstance(analysis_result, dict):
                analysis_result = {}
            
            # 补充默认值，并整合Legal-BERT的分析结果
            result = {
                "thinking_quality_score": analysis_result.get("thinking_quality_score", 70),
                "strengths": analysis_result.get("strengths", []),
                "weaknesses": analysis_result.get("weaknesses", []),
                "thinking_pattern": analysis_result.get("thinking_pattern", "需要进一步分析"),
                "reasoning_chain": reasoning_chain,  # 使用Legal-BERT提取的推理链条
                "reasoning_completeness": reasoning_completeness,
                "key_facts": key_facts,  # Legal-BERT提取的关键事实
                "legal_entities": entities,  # Legal-BERT提取的法律实体
                "improvement_suggestions": analysis_result.get("improvement_suggestions", []),
                "legal_knowledge_gaps": analysis_result.get("legal_knowledge_gaps", []),
                "analysis_timestamp": datetime.now().isoformat(),
                "bert_enhanced": True  # 标记使用了Legal-BERT增强
            }
            
            # 保存思维分析记录
            await self._save_thinking_analysis(user_id, question_id, result)
            
            return result
            
        except Exception as e:
            print(f"思维分析错误: {e}")
            # 返回默认分析结果
            return {
                "thinking_quality_score": 70,
                "strengths": ["能够尝试分析问题"],
                "weaknesses": ["需要加强法律条文理解"],
                "thinking_pattern": "基础思维模式",
                "reasoning_chain": "推理过程需要完善",
                "improvement_suggestions": [
                    "加强法律条文的学习和理解",
                    "提高逻辑推理能力",
                    "多进行案例分析训练"
                ],
                "legal_knowledge_gaps": [],
                "analysis_timestamp": datetime.now().isoformat(),
                "error": str(e)
            }
    
    def _parse_thinking_analysis(self, text: str) -> Dict[str, Any]:
        """解析文本格式的思维分析结果"""
        # 简单的文本解析逻辑
        result = {
            "thinking_quality_score": 70,
            "strengths": [],
            "weaknesses": [],
            "thinking_pattern": "基础思维模式",
            "reasoning_chain": "推理过程需要完善",
            "improvement_suggestions": [],
            "legal_knowledge_gaps": []
        }
        
        # 尝试从文本中提取关键信息
        if "优势" in text or "strength" in text.lower():
            result["strengths"].append("能够尝试分析问题")
        if "薄弱" in text or "weakness" in text.lower():
            result["weaknesses"].append("需要加强法律条文理解")
        
        return result
    
    async def _save_thinking_analysis(
        self,
        user_id: str,
        question_id: str,
        analysis: Dict[str, Any]
    ):
        """保存思维分析记录"""
        if self.redis is None:
            # Redis不可用时，跳过保存（不影响主流程）
            return
        try:
            key = f"thinking_analysis:{user_id}:{question_id}"
            # 将分析结果序列化存储
            import json
            self.redis.setex(
                key,
                86400 * 30,  # 保存30天
                json.dumps(analysis, ensure_ascii=False)
            )
        except Exception as e:
            # Redis操作失败时，记录错误但不影响主流程
            print(f"保存思维分析记录失败: {e}")
    
    async def generate_thinking_training_plan(
        self,
        user_id: str,
        time_period_days: int = 30
    ) -> Dict[str, Any]:
        """
        生成法律思维训练计划
        
        Args:
            user_id: 用户ID
            time_period_days: 训练周期（天数）
            
        Returns:
            训练计划
        """
        # 获取用户的历史思维分析数据
        thinking_scores = await self._get_thinking_scores(user_id, time_period_days)
        
        # 分析薄弱环节
        avg_score = sum(thinking_scores) / len(thinking_scores) if thinking_scores else 70
        
        # 生成训练计划
        training_plan = {
            "user_id": user_id,
            "period_days": time_period_days,
            "current_thinking_score": avg_score,
            "target_score": min(90, avg_score + 10),
            "training_focus": self._determine_training_focus(avg_score, thinking_scores),
            "daily_tasks": self._generate_daily_tasks(avg_score),
            "weekly_milestones": self._generate_weekly_milestones(time_period_days),
            "recommended_resources": self._get_recommended_resources(avg_score)
        }
        
        return training_plan
    
    async def _get_thinking_scores(
        self,
        user_id: str,
        days: int
    ) -> List[float]:
        """获取用户的历史思维质量分数"""
        # 从Redis获取最近的思维分析记录
        pattern = f"thinking_analysis:{user_id}:*"
        keys = []
        
        # 简化实现：返回模拟数据
        # 实际应该从Redis查询并解析
        return [70.0, 72.0, 75.0, 73.0, 76.0]
    
    def _determine_training_focus(
        self,
        avg_score: float,
        scores: List[float]
    ) -> List[str]:
        """确定训练重点"""
        focus_areas = []
        
        if avg_score < 60:
            focus_areas.extend([
                "法律基础概念理解",
                "法律条文记忆和应用",
                "基础逻辑推理训练"
            ])
        elif avg_score < 75:
            focus_areas.extend([
                "案例分析能力提升",
                "法律思维模式建立",
                "推理链条完整性训练"
            ])
        else:
            focus_areas.extend([
                "高级法律推理训练",
                "复杂案例分析",
                "法律思维创新"
            ])
        
        return focus_areas
    
    def _generate_daily_tasks(self, current_score: float) -> List[Dict[str, Any]]:
        """生成每日训练任务"""
        tasks = []
        
        if current_score < 70:
            tasks = [
                {
                    "task_type": "concept_review",
                    "description": "复习3-5个法律基础概念",
                    "duration_minutes": 30
                },
                {
                    "task_type": "case_analysis",
                    "description": "分析2个典型案例",
                    "duration_minutes": 45
                },
                {
                    "task_type": "reasoning_practice",
                    "description": "完成10道推理训练题",
                    "duration_minutes": 30
                }
            ]
        else:
            tasks = [
                {
                    "task_type": "advanced_case",
                    "description": "分析1个复杂案例",
                    "duration_minutes": 60
                },
                {
                    "task_type": "legal_reasoning",
                    "description": "完成5道高级推理题",
                    "duration_minutes": 40
                },
                {
                    "task_type": "thinking_reflection",
                    "description": "反思和总结思维过程",
                    "duration_minutes": 20
                }
            ]
        
        return tasks
    
    def _generate_weekly_milestones(self, total_days: int) -> List[Dict[str, Any]]:
        """生成每周里程碑"""
        weeks = (total_days + 6) // 7
        milestones = []
        
        for week in range(1, weeks + 1):
            milestones.append({
                "week": week,
                "target_score": 70 + (week * 2),
                "focus": f"第{week}周重点训练",
                "checkpoint": f"week_{week}"
            })
        
        return milestones
    
    def _get_recommended_resources(self, current_score: float) -> List[Dict[str, Any]]:
        """获取推荐学习资源"""
        resources = [
            {
                "type": "textbook",
                "title": "法律思维训练指南",
                "description": "系统学习法律思维方法",
                "priority": "high" if current_score < 70 else "medium"
            },
            {
                "type": "case_study",
                "title": "典型案例分析集",
                "description": "通过案例训练法律思维",
                "priority": "high"
            },
            {
                "type": "video",
                "title": "法律推理技巧视频",
                "description": "观看法律推理教学视频",
                "priority": "medium" if current_score < 75 else "low"
            }
        ]
        
        return resources
    
    async def provide_thinking_feedback(
        self,
        user_id: str,
        question_id: str,
        user_thinking: str,
        question_content: Optional[str] = None
    ) -> Dict[str, Any]:
        """
        提供实时思维反馈
        
        Args:
            user_id: 用户ID
            question_id: 题目ID
            user_thinking: 用户的思考过程
            question_content: 题目内容（可选，用于增强分析）
            
        Returns:
            反馈结果
        """
        # 如果提供了题目内容，使用Legal-BERT进行分析
        bert_insights = None
        if question_content:
            try:
                # 提取推理链条
                reasoning_chain = await self.legalbert.extract_legal_reasoning_chain(
                    question_content,
                    user_thinking
                )
                
                # 提取关键事实
                key_facts = await self.legalbert.extract_key_facts(question_content)
                
                # 检测陷阱
                traps = await self.legalbert.detect_question_traps(question_content)
                
                bert_insights = {
                    "reasoning_chain": reasoning_chain,
                    "key_facts": key_facts,
                    "traps": traps,
                    "reasoning_completeness": reasoning_chain.get("reasoning_completeness", {})
                }
            except Exception as e:
                print(f"Legal-BERT分析错误: {e}")
        
        feedback_prompt = f"""
学员正在思考一道法律题目，请提供实时反馈和引导。

【学员的思考过程】
{user_thinking}
"""
        
        if bert_insights:
            feedback_prompt += f"""
【Legal-BERT分析结果】
- 推理链条完整性：{bert_insights['reasoning_completeness'].get('level', '未知')}
- 已识别关键事实：{len(bert_insights['key_facts'])} 个
- 检测到陷阱：{len(bert_insights['traps'])} 个
"""
        
        feedback_prompt += """
请提供：
1. 思维方向是否正确？
2. 是否需要补充关键信息？
3. 推理过程是否有遗漏？
4. 下一步应该思考什么？

请以鼓励和引导的方式提供反馈。
"""
        
        try:
            feedback = await self.llm_service.analyze_legal_case(feedback_prompt)
            
            result = {
                "feedback_text": feedback if isinstance(feedback, str) else "继续思考，你已经走在正确的道路上！",
                "suggestions": self._extract_suggestions(feedback if isinstance(feedback, str) else ""),
                "encouragement": True,
                "bert_insights": bert_insights  # 包含Legal-BERT的分析结果
            }
            
            # 如果推理链条不完整，提供针对性建议
            if bert_insights and bert_insights['reasoning_completeness'].get('score', 100) < 66:
                result["suggestions"].append("建议补充推理链条中缺失的部分（大前提、小前提或结论）")
            
            return result
        except Exception as e:
            return {
                "feedback_text": "保持思考，法律思维需要不断练习！",
                "suggestions": ["尝试从法律条文入手", "分析案例中的关键事实"],
                "encouragement": True,
                "error": str(e),
                "bert_insights": bert_insights
            }
    
    def _extract_suggestions(self, text: str) -> List[str]:
        """从反馈文本中提取建议"""
        suggestions = []
        # 简单的文本提取逻辑
        if "建议" in text:
            suggestions.append("参考系统建议")
        if "注意" in text:
            suggestions.append("注意关键点")
        return suggestions


legal_thinking_service = LegalThinkingService()

